#include "musiclist.h"
#include <QMimeDatabase>
#include <QMimeType>
#include <QDebug>
#include <QFileInfo>
#include <QSqlQuery>
MusicList::MusicList()
{

}

void MusicList::addMusicByUrl(const QList<QUrl> &urls)
{
    for(auto e : urls)
    {
        QString musicPath = e.toLocalFile();
        qDebug() << musicPath;
        // 检测歌曲是否存在，如果再才能添加
        if(musicPaths.contains(musicPath))
            continue;
        // 歌曲还没有加载过，将其解析并添加到歌曲列表
        musicPaths.insert(musicPath);
        // 如果musicUrl是⼀个有效的歌曲⽂件，再将其添加到歌曲列表中
        // 检测歌曲⽂件的MIME类型

        QMimeDatabase db;
        QMimeType mime = db.mimeTypeForFile(e.toLocalFile());
        if(mime.name() != "audio/mpeg" && mime.name() != "audio/flac")
            continue;
        musicList.push_back(e);
        qDebug() <<e;
    }
}

iterator MusicList::begin()
{
    return musicList.begin();
}

iterator MusicList::end()
{
    return musicList.end();
}

iterator MusicList::findMusicById(const QString &musicId)
{
    for(iterator it = begin(); it != end(); ++it)
    {
        if(it->getMusicId() == musicId)
        {
            return it;
        }
    }
    return end();
}

void MusicList::writeToDB()
{
    for(auto music : musicList)
    {
    // 让music对象将⾃⼰写⼊数据库
        music.insertMusicToDB();
    }
}

void MusicList::readFromDB()
{
    QString sql("SELECT musicId, musicName, musicSinger, albumName,\
    duration, musicUrl, isLike, isHistory \
    FROM musicInfo");
    QSqlQuery query;
    if(!query.exec(sql))
    {
        qDebug()<<"数据库查询失败";
        return;
    }
    while(query.next())
    {
        Music music;
        music.setMusicId(query.value(0).toString());
        music.setMusicName(query.value(1).toString());
        music.setSingerName(query.value(2).toString());
        music.setAlbumName(query.value(3).toString());
        music.setDuration(query.value(4).toLongLong());
        music.setMusicUrl("file:///" + query.value(5).toString());
        music.setIsLike(query.value(6).toBool());
        music.setIsHistory(query.value(7).toBool());
        musicList.push_back(music);
        musicPaths.insert(music.getMusicUrl().toLocalFile());
    }
}
